package com.sky.service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dao.CategoryDTO;
import com.sky.dao.CategoryPageDTO;
import com.sky.entity.Category;
import com.sky.exception.NoNullException;
import com.sky.mapper.CategoryMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetmealMapper setmealMapper;

    @Override
    public PageResult page(CategoryPageDTO categoryPageDTO) {
        PageHelper.startPage(categoryPageDTO.getPage(), categoryPageDTO.getPageSize());
        Page<Category> page = categoryMapper.page(categoryPageDTO);
        PageResult pageResult = new PageResult();
        pageResult.setTotal(page.getTotal());
        pageResult.setRecords(page.getResult());
        return pageResult;
    }

    @Override
    public List<Category> list(Integer type) {
        return categoryMapper.list(type);
    }

    @Override
    public void update(CategoryDTO categoryDTO) {
        categoryMapper.update(categoryDTO);
    }

    @Override
    public void startOrStop(Integer status, Integer id) {
        categoryMapper.startOrStop(status, id);
    }

    @Override
    public void delete(Integer id) {
        //根據id查詢type
        Integer type = categoryMapper.getType(id);
        Integer count = 0;
        //菜品
        if (type == 1) {
            count = dishMapper.count(id);
        } else if (type == 2) {
            count = setmealMapper.count(id);
        }
        if (count != 0) {
            throw new NoNullException(MessageConstant.CAN_DELETE);
        }else if (count == 0) {
            categoryMapper.delete(id);
        }
    }

    @Override
    public void save(CategoryDTO categoryDTO) {
        Category category = new Category();
        BeanUtils.copyProperties(categoryDTO, category);
        category.setStatus(StatusConstant.ENABLE);
        categoryMapper.save(category);
    }


}
